package com.sabre.workshop.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A singleton to obtain an EntityManager object from a proper factory. The
 * factory is bound to a single persistence unit and this class can only handle
 * one persistence unit.
 * 
 * @author mgore
 * 
 */
public class EntityManagerUtil {

	private final static String PERSISTENCE_UNIT_NAME = "Sabre-Taller";

	private Log log = LogFactory.getFactory().getInstance(this.getClass());

	private EntityManagerFactory entityManagerFactory;

	public EntityManagerUtil() {

		log.debug("Creating an EntityManagerFactory. This message shouldn't appear more than once.");
		this.getEntityManagerFactory();
	}

	private EntityManagerFactory getEntityManagerFactory() {

		if (entityManagerFactory == null) {

			entityManagerFactory = Persistence
					.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		}

		return entityManagerFactory;
	}

	public EntityManager getEntityManager() {

		EntityManager entityManager = this.getEntityManagerFactory()
				.createEntityManager();
		log.trace("Giving out " + entityManager);

		return entityManager;
	}

}
